import React, { useState, useRef } from 'react';
import { Card, Button, Space, Select, Divider, Typography } from 'antd';
import {
  BoldOutlined,
  ItalicOutlined,
  UnderlineOutlined,
  StrikethroughOutlined,
  LinkOutlined,
  UnorderedListOutlined,
  OrderedListOutlined,
  UndoOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { ListPlugin } from '@lexical/react/LexicalListPlugin';
import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { MarkdownShortcutPlugin } from '@lexical/react/LexicalMarkdownShortcutPlugin';
import { TabIndentationPlugin } from '@lexical/react/LexicalTabIndentationPlugin';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';
import { HorizontalRuleNode } from '@lexical/react/LexicalHorizontalRuleNode';
import { CodeNode, CodeHighlightNode } from '@lexical/code';
import { TRANSFORMERS } from '@lexical/markdown';
import {
  $getSelection,
  $isRangeSelection,
  FORMAT_TEXT_COMMAND,
  UNDO_COMMAND,
  REDO_COMMAND,
  $getRoot,
} from 'lexical';
import {
  INSERT_UNORDERED_LIST_COMMAND,
  INSERT_ORDERED_LIST_COMMAND,
  ListNode,
  ListItemNode,
} from '@lexical/list';
import { LinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';
import {
  HeadingNode,
  QuoteNode,
} from '@lexical/rich-text';



const { Title, Paragraph } = Typography;

// 简化的编辑器主题
const theme = {
  text: {
    bold: 'editor-text-bold',
    italic: 'editor-text-italic',
    underline: 'editor-text-underline',
    strikethrough: 'editor-text-strikethrough',
  },
  list: {
    ol: 'editor-list-ol',
    ul: 'editor-list-ul',
    listitem: 'editor-listitem',
  },
  link: 'editor-link',
};

// 编辑器配置
const editorConfig = {
  namespace: 'LexicalEditor',
  theme,
  nodes: [ListNode, ListItemNode, LinkNode, QuoteNode, HeadingNode, HorizontalRuleNode, CodeNode, CodeHighlightNode] as any,
  onError: (error: Error) => {
    console.error('Lexical Error:', error);
  },
};

function ToolbarPlugin() {
  const [editor] = useLexicalComposerContext();
  const [isBold, setIsBold] = useState(false);
  const [isItalic, setIsItalic] = useState(false);
  const [isUnderline, setIsUnderline] = useState(false);
  const [isStrikethrough, setIsStrikethrough] = useState(false);

  // 监听选择变化
  React.useEffect(() => {
    return editor.registerUpdateListener(({ editorState }) => {
      editorState.read(() => {
        const selection = $getSelection();
        if ($isRangeSelection(selection)) {
          setIsBold(selection.hasFormat('bold'));
          setIsItalic(selection.hasFormat('italic'));
          setIsUnderline(selection.hasFormat('underline'));
          setIsStrikethrough(selection.hasFormat('strikethrough'));
        }
      });
    });
  }, [editor]);

  // 格式化文本
  const formatText = (format: 'bold' | 'italic' | 'underline' | 'strikethrough') => {
    editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
  };

  // 插入链接
  const insertLink = () => {
    const url = prompt('请输入链接地址:');
    if (url) {
      editor.dispatchCommand(TOGGLE_LINK_COMMAND, url);
    }
  };

  // 插入列表
  const insertList = (listType: 'bullet' | 'number') => {
    if (listType === 'bullet') {
      editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
    } else {
      editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
    }
  };

  // 撤销重做
  const undo = () => {
    editor.dispatchCommand(UNDO_COMMAND, undefined);
  };

  const redo = () => {
    editor.dispatchCommand(REDO_COMMAND, undefined);
  };

  return (
    <div className="toolbar" style={{ padding: '12px', borderBottom: '1px solid #d9d9d9', backgroundColor: '#fafafa' }}>
      <Space wrap>
        <Button
          size="small"
          type={isBold ? 'primary' : 'default'}
          icon={<BoldOutlined />}
          onClick={() => formatText('bold')}
        />
        <Button
          size="small"
          type={isItalic ? 'primary' : 'default'}
          icon={<ItalicOutlined />}
          onClick={() => formatText('italic')}
        />
        <Button
          size="small"
          type={isUnderline ? 'primary' : 'default'}
          icon={<UnderlineOutlined />}
          onClick={() => formatText('underline')}
        />
        <Button
          size="small"
          type={isStrikethrough ? 'primary' : 'default'}
          icon={<StrikethroughOutlined />}
          onClick={() => formatText('strikethrough')}
        />
        <Divider type="vertical" />
        <Button
          size="small"
          icon={<UnorderedListOutlined />}
          onClick={() => insertList('bullet')}
        />
        <Button
          size="small"
          icon={<OrderedListOutlined />}
          onClick={() => insertList('number')}
        />
        <Button size="small" icon={<LinkOutlined />} onClick={insertLink} />
        <Divider type="vertical" />
        <Button size="small" icon={<UndoOutlined />} onClick={undo} />
        <Button size="small" icon={<RedoOutlined />} onClick={redo} />
      </Space>
    </div>
  );
}

function MyOnChangePlugin({ onChange }: { onChange: (editorState: any) => void }) {
  const [editor] = useLexicalComposerContext();
  return (
    <OnChangePlugin
      onChange={(editorState) => {
        onChange(editorState);
      }}
    />
  );
}

function GetContentButton() {
  const [editor] = useLexicalComposerContext();
  
  const handleGetContent = () => {
    editor.update(() => {
      const root = $getRoot();
      const selection = $getSelection();
      console.log('Lexical content:', root.getTextContent());
      console.log('Selection:', selection);
    });
  };

  return (
    <Button onClick={handleGetContent}>获取内容</Button>
  );
}

const LexicalPage: React.FC = () => {

  // 添加基础样式
  React.useEffect(() => {
    const style = document.createElement('style');
    style.textContent = `
      .editor-text-bold {
        font-weight: bold;
      }
      .editor-text-italic {
        font-style: italic;
      }
      .editor-text-underline {
        text-decoration: underline;
      }
      .editor-text-strikethrough {
        text-decoration: line-through;
      }
      .editor-list-ol {
        padding-left: 1.5em;
        margin: 1em 0;
      }
      .editor-list-ul {
        padding-left: 1.5em;
        margin: 1em 0;
      }
      .editor-listitem {
        margin: 0.25em 0;
      }
      .editor-link {
        color: #1890ff;
        text-decoration: none;
      }
      .editor-link:hover {
        text-decoration: underline;
      }
    `;
    document.head.appendChild(style);
    return () => {
      document.head.removeChild(style);
    };
  }, []);

  const onChange = (editorState: any) => {
    editorState.read(() => {
      const root = $getRoot();
      const textContent = root.getTextContent();
      // console.log('Content changed:', textContent);
    });
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={2}>Lexical 富文本编辑器 - 模块化架构</Title>
        <Paragraph>
          基于 Facebook 的 Lexical 框架构建的现代富文本编辑器，采用模块化插件架构。
          <br />
          <strong>核心特性：</strong>
          <br />
          • 模块化插件系统：RichTextPlugin、HistoryPlugin、ListPlugin、LinkPlugin
          <br />
          • 自动聚焦：AutoFocusPlugin 提供编辑器自动聚焦
          <br />
          • Markdown 快捷键：MarkdownShortcutPlugin 支持 Markdown 语法
          <br />
          • Tab 缩进：TabIndentationPlugin 支持 Tab 键缩进
          <br />
          • 文本格式化：粗体、斜体、下划线、删除线
          <br />
          • 列表支持：有序列表和无序列表
          <br />
          • 链接功能：支持超链接插入和编辑
          <br />
          • 历史记录：完整的撤销/重做功能
          <br />
          • 实时状态：OnChangePlugin 监听编辑器状态变化
        </Paragraph>
        
        <div style={{ marginTop: '20px' }}>
          <LexicalComposer initialConfig={editorConfig}>
            <ToolbarPlugin />
            <div style={{ position: 'relative', border: '1px solid #d9d9d9', borderRadius: '0 0 6px 6px', borderTop: 'none', padding: '12px', minHeight: '200px' }}>
              <RichTextPlugin
                contentEditable={<ContentEditable style={{ outline: 'none', minHeight: '150px' }} />}
                placeholder={<div style={{ position: 'absolute', top: '12px', left: '12px', color: '#999', pointerEvents: 'none' }}>请输入内容...</div>}
                ErrorBoundary={LexicalErrorBoundary}
              />
              <HistoryPlugin />
              <ListPlugin />
              <LinkPlugin />
              <AutoFocusPlugin />
                <TabIndentationPlugin />
                <MarkdownShortcutPlugin transformers={TRANSFORMERS} />
                <OnChangePlugin onChange={(editorState) => {
                  console.log('Editor state changed:', editorState);
                }} />
            </div>
            
            <div style={{ marginTop: '20px' }}>
              <GetContentButton />
            </div>
          </LexicalComposer>
        </div>
      </Card>
    </div>
  );
};

export default LexicalPage;